﻿namespace EHSubmit.Logic.LINQ
{
    using System;
    using System.Data;
    using System.Configuration;
    using System.Linq;
    using System.Collections.Generic;

    /// <summary>
    /// 题目数据库操作
    /// </summary>
    public class QuestionManager
    {
        public QuestionManager()
        {
        }


        /// <summary>
        /// 获得某次作业的客观题[不含选项](必须为客观题类型)
        /// </summary>
        /// <param name="goalId">所布置作业的ID</param>
        /// <returns>题目列表</returns>
        public IList<Question> GetQuestionsWithoutOptions(int goalId)
        {
            EHSubmitDataContext db = new EHSubmitDataContext(EHSubmit.Util.SqlHelper.ConnectionStringLocalTransaction);

            IList<Question> ques = (from q in db.Question
                                    join gq in db.GoalQuestion
                                    on new { GID = goalId, QID = q.QID } equals new { GID = gq.GoalID, QID = gq.QuestionID }
                                    select q
                                    ).ToList<Question>();

            return ques;
        }
        /// <summary>
        /// 获得某次作业的客观题(必须为客观题类型)
        /// </summary>
        /// <param name="goalId">所布置作业的ID</param>
        /// <returns>题目列表</returns>
        public IList<Question> GetQuestions(int goalId)
        {
            EHSubmitDataContext db = new EHSubmitDataContext(EHSubmit.Util.SqlHelper.ConnectionStringLocalTransaction);

            IList<Question> ques = (from q in db.Question
                                         from opt in q.Options
                                         //from gq in q.GoalQuestion
                                         join gq in db.GoalQuestion
                                         on new { GID = goalId, QID = q.QID } equals new { GID = gq.GoalID, QID = gq.QuestionID}
                                         select q
                                        ).Distinct().ToList<Question>();

           
            /*
            IList<Question> questions = (
                                         from gq in db.GoalQuestion
                                         from q in gq.Question
                                         from opt in q.Options
                                         where gq.GoalID == goalId
                                         select q
                                         ).ToList<Question>();
            */
            return ques;
        }

        /// <summary>
        /// 添加习题
        /// </summary>
        /// <param name="qes">习题</param>
        /// <param name="opts">习题的相关选项</param>
        public int AddQuestion(Question qes,IList<Options> opts)
        {
            try
            {
                #region 原来的实现
                //int i;
                //SqlParameter[] parms = new SqlParameter[12];
                //parms[0] = new SqlParameter(PARM_OwnerID, SqlDbType.NVarChar, 13);       /*习题提供者的ID*/
                //parms[1] = new SqlParameter(PARM_Type, SqlDbType.Int);                   /*习题类型*/
                //parms[2] = new SqlParameter(PARM_Content, SqlDbType.NVarChar, 300);      /*题目内容,一般是不允许出现类似英语试卷的那种大题，应该是最简单的单选或多选*/
                //parms[3] = new SqlParameter(PARM_Answer, SqlDbType.NVarChar, 4);         /*标答,这里限定答案里的选项最多不得超过四个*/
                //parms[4] = new SqlParameter(PARM_UpdateTime, SqlDbType.DateTime);        /*习题更新的时间*/
                //parms[5] = new SqlParameter(PARM_RightCount, SqlDbType.Int);             /*习题答对的人数统计*/
                //parms[6] = new SqlParameter(PARM_WrongCount, SqlDbType.Int);             /*习题答错的人数统计*/
                //parms[7] = new SqlParameter(PARM_Rate, SqlDbType.Float);                 /*正确率*/
                //parms[8] = new SqlParameter(PARM_BaseCourseID, SqlDbType.NVarChar, 10);  /*习题第一次被添加时所属的课程号，注：非课程ID*/
                //parms[9] = new SqlParameter(PARM_Institute, SqlDbType.Int);              /*习题适用的范围，即对应的学院*/
                //parms[10] = new SqlParameter(PARM_Department, SqlDbType.Int);            /*习题适用的范围，即对应的专业*/
                //parms[11] = new SqlParameter(PARM_Tag, SqlDbType.NVarChar,50);           /*习题中关键词（暂时不需要*/
                //parms[0].Value = qes.OwnerID;
                //parms[1].Value = qes.Type;
                //parms[2].Value = qes.Content;
                //parms[3].Value = qes.Answer;
                //parms[4].Value = qes.UpdateTime;
                //parms[5].Value = qes.RightCount;
                //parms[6].Value = qes.WrongCount;
                //parms[7].Value = qes.Rate;
                //parms[8].Value = qes.BaseCourseID;
                //parms[9].Value = qes.Institute;
                //parms[10].Value = qes.Department;
                //parms[11].Value = qes.Tag;

                //i = (int)SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_INSERT_Question, parms);
                #endregion
                int qid = -1;
                using(EHSubmitDataContext eDataContext = new EHSubmitDataContext(EHSubmit.Util.SqlHelper.ConnectionStringLocalTransaction))
                {
                    eDataContext.Question.InsertOnSubmit(qes);
                    eDataContext.SubmitChanges();

                    //添加习题中选项
                    qid = qes.QID;
                    foreach (Options opt in opts)
                    {
                        opt.QID = qid;
                    }
                    eDataContext.Options.InsertAllOnSubmit(opts);
                    eDataContext.SubmitChanges();
                }
                return qid;
            }
            catch
            {
                EHSubmit.Util.LogHelper.Log("数据插入错误!");
                return -1;
            }
        }

        /// <summary>
        /// 按条件获取习题(习题仅属于个人)
        /// </summary>
        /// <returns>获取的习题中还包含出题者姓名</returns>
        public IList<Question> GetQuestionsByCondition(string baseCourseID,string ownerID)
        {
            try
            {
                //IList<object> objList = new List<object>();
                IList<Question> qesList = new List<Question>();
                EHSubmitDataContext db = new EHSubmitDataContext(EHSubmit.Util.SqlHelper.ConnectionStringLocalTransaction);
                qesList = (db.Question.Where(q => (q.OwnerID == ownerID && q.BaseCourseID == baseCourseID))).ToList<Question>();

                //UserManager userManager = new UserManager();
                //EHSubmit.Model.User user = userManager.GetUser(ownerID);
                //foreach (Question qes in qesList)
                //{
                //    IList<Options> options = db.Options.Where(opt => opt.QID == qes.QID).ToList<Options>();
                //    object o = new { qes.QID, qes.OwnerID, qes.Type, qes.Content, qes.Answer, qes.UpdateTime, qes.RightCount, qes.WrongCount, qes.Rate, qes.BaseCourseID, qes.Institute, qes.Tag, options, OwnerName = user.Name };
                //    //object o = new { qes, OwnerName = user.Name };
                //    objList.Add(o);
                //}
                return qesList;
            }
            catch (Exception ex)
            {
                EHSubmit.Util.LogHelper.Log(ex.Message,ex);
                return null;
            }
        }

        /// <summary>
        /// 根据ID获取习题信息
        /// </summary>
        /// <param name="qid"></param>
        /// <returns></returns>
        public IList<Question> GetQuestion(int qid)
        {
            try
            {
                //---与数据库的连接保持，才能继续获取options的数据
                IList<Question> qes = null;
                EHSubmitDataContext db = new EHSubmitDataContext(EHSubmit.Util.SqlHelper.ConnectionStringLocalTransaction);

                qes = (db.Question.Where(q => (q.QID == qid))).ToList<Question>();

                return qes;
            }
            catch (Exception ex)
            {
                EHSubmit.Util.LogHelper.Log(ex.Message, ex);
                return null;
            }
        }

        /// <summary>
        /// 删除习题
        /// </summary>
        /// <param name="qid"></param>
        public void DeleteQuestion(int qid)
        {
            try
            {
                if (qid == -1)
                {
                    EHSubmit.Util.LogHelper.Log("习题ID不正确");
                }
                else
                {
                    using (EHSubmitDataContext db = new EHSubmitDataContext(EHSubmit.Util.SqlHelper.ConnectionStringLocalTransaction))
                    {
                        IList<Question> deleteQuestion = (from q in db.Question
                                                          where q.QID == qid
                                                          select q).ToList<Question>();

                        foreach (Question question in deleteQuestion)
                        {
                            db.Question.DeleteOnSubmit(question);
                        }

                        db.SubmitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                EHSubmit.Util.LogHelper.Log(ex.Message, ex);
            }
        }
    }
}